package io.github.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import io.github.entity.SysRoleEntity;
import io.github.service.SysRoleMenuService;
import io.github.service.SysRoleService;
import io.github.util.DateUtils;
import io.github.util.JoeyUtil;
import io.github.util.PageUtils;
import io.github.util.R;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

/**
 * 角色管理
 */
@RestController
@RequestMapping("/admin/sys/role")
public class SysRoleController extends AbstractController {

    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 角色列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestBody JSONObject jsonObject) {
        logger.info("获取角色接口");
        Integer offset = jsonObject.getInteger("offset");
        Integer limit = jsonObject.getInteger("limit");
        //角色集合
        List<Long> menuIdList = new ArrayList<>();
        Page<SysRoleEntity> roleList = sysRoleService.queryListByPage(offset, limit);

        //获取角色集合
        List<SysRoleEntity> records = roleList.getRecords();

        for (int i = 0; i < records.size(); i++) {
            //获取角色
            Long roleId = records.get(i).getRoleId();
            menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
            //设置菜单集合
            records.get(i).setMenuIdList(menuIdList);
        }
        PageUtils pageUtil = new PageUtils(records, roleList.getTotal(), roleList.getSize(),
                roleList.getCurrent());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 角色列表
     */
    @RequestMapping("/select")
    @RequiresPermissions("sys:role:select")
    public R select() {
        // 查询列表数据
        List<SysRoleEntity> list = sysRoleService.queryList(new HashMap<String, Object>(0));

        return R.ok().put("list", list);
    }

    /**
     * 根据角色名模糊查询
     */
    @RequestMapping("/roleName")
    @ResponseBody
    public R query(@RequestBody JSONObject jsonObject) {
        logger.info("根据角色名查询接口");
        String roleName = jsonObject.getString("roleName");
        Integer offset = jsonObject.getInteger("offset");
        Integer limit = jsonObject.getInteger("limit");
        //角色集合
        List<Long> menuIdList = new ArrayList<>();
        Page<SysRoleEntity> roleList = sysRoleService.queryListByPage(offset, limit, roleName);
        //获取角色集合
        List<SysRoleEntity> records = roleList.getRecords();

        for (int i = 0; i < records.size(); i++) {
            //获取角色
            Long roleId = records.get(i).getRoleId();
            menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
            //设置菜单集合
            records.get(i).setMenuIdList(menuIdList);
        }
        PageUtils pageUtil = new PageUtils(records, roleList.getTotal(), roleList.getSize(),
                roleList.getCurrent());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 角色信息
     */
    @RequestMapping("/info/{roleId}")
    @RequiresPermissions("sys:role:info")
    public R info(@PathVariable("roleId") Long roleId) {
        SysRoleEntity role = sysRoleService.selectById(roleId);

        // 查询角色对应的菜单
        List<Long> menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
        role.setMenuIdList(menuIdList);

        return R.ok().put("role", role);
    }

    /**
     * 保存角色
     *
     * @throws ParseException
     */
    @RequestMapping("/save")
    @ResponseBody
    public R save(@RequestBody JSONObject jsonObject) throws ParseException {
        logger.info("创建/保存角色接口");
        //获取json数据
        String roleName = jsonObject.getString("roleName");
        String remark = jsonObject.getString("remark");
        String menuIdStr = jsonObject.getString("ids");
        System.out.println(">>>>>menuIdStr:" + menuIdStr);
        String ids = "[" + menuIdStr + "]";
        System.out.println(">>>>>ids:" + ids);
        if (StringUtils.isBlank(roleName)) {
            return R.error(500, "角色名称不能为空");
        }
        SysRoleEntity roleEntity = new SysRoleEntity();
        roleEntity.setRoleName(roleName);
        roleEntity.setRemark(remark);
        roleEntity.setCreateTime(JoeyUtil.stampDate(new Date(), DateUtils.DATE_TIME_PATTERN));

        JSONArray jsonArray = JSONArray.parseArray(ids);
        Long[] menuId = toArrays(jsonArray);
        List<Long> menuIds = new ArrayList<Long>();
        Collections.addAll(menuIds, menuId);
        if (menuIds.size() < 0) {
            sysRoleService.saveRole(roleEntity);
            return R.ok().put("role", roleEntity);
        }
        roleEntity.setMenuIdList(menuIds);
        sysRoleService.save(roleEntity);
        return R.ok().put("role", roleEntity);
    }

    /**
     * 修改角色
     */
    @RequestMapping("/update")
    @ResponseBody
    public R update(@RequestBody JSONObject jsonObject) {
        logger.info("角色信息修改接口");
        Long roleId = jsonObject.getLong("roleId");
        String roleName = jsonObject.getString("roleName");
        String remark = jsonObject.getString("remark");
        //菜单id
        String menuIdStr = jsonObject.getString("menuIds");
        System.out.println(">>>>>menuIdStr:" + menuIdStr);
        String ids = "[" + menuIdStr + "]";
        System.out.println(">>>>>ids:" + ids);
        if (StringUtils.isBlank(roleName)) {
            return R.error(500, "角色名称不能为空");
        }
        SysRoleEntity roleEntity = new SysRoleEntity();
        roleEntity.setRoleId(roleId);
        roleEntity.setRoleName(roleName);
        roleEntity.setRemark(remark);

        JSONArray jsonArray = JSONArray.parseArray(ids);
        Long[] menuId = toArrays(jsonArray);
        List<Long> menuIds = new ArrayList<Long>();
        Collections.addAll(menuIds, menuId);
        if (menuIds.size() < 0) {
            sysRoleService.updateRole(roleEntity);
            return R.ok().put("role", roleEntity);
        }
        roleEntity.setMenuIdList(menuIds);

        sysRoleService.update(roleEntity);

        return R.ok().put("role", roleEntity);
    }

    /**
     * 删除角色
     */
    @RequestMapping("/delete")
    @ResponseBody
    public R delete(@RequestBody JSONObject jsonObject) {
        logger.info("角色删除接口");
        //roleIdStr:17,18
        String roleIdStr = jsonObject.getString("roleIds");
        //ids:[18,17]
        String ids = "[" + roleIdStr + "]";
        System.out.println(">>>>>ids:" + ids);
        JSONArray jsonArray = JSONArray.parseArray(ids);
        Long[] roleIds = toArrays(jsonArray);
        sysRoleService.deleteBatch(roleIds);
        return R.ok();
    }

}
